import { defineStore } from 'pinia'
import { loginRequest } from '@/api/login'
import type { LoginForm } from '@/api/login/type'
import { ref } from 'vue'

// 第一个参数是你的应用中 Store 的唯一 ID。
export const useUserStore = defineStore('userStore', () => {
  // 用户头像
  const avatar = ref(localStorage.getItem('avatar'))
  const username = ref(localStorage.getItem('username'))
  const permissions = ref(localStorage.getItem('permissions'))
  const token = ref(localStorage.getItem('token'))
  const buttons = ref(localStorage.getItem('buttons'))
  // 登录方法
  async function login(data: LoginForm) {
    await loginRequest(data)
      .then((res) => {
        username.value = res.username as string
        avatar.value = res.avatar as string
        permissions.value = res.permissions.toString()
        token.value = res.token as string
        localStorage.setItem('avatar', res.avatar as string)
        localStorage.setItem('token', res.token as string)
        localStorage.setItem('username', res.username as string)
        localStorage.setItem('permissions', res.permissions.toString())
        localStorage.setItem('buttons', res.buttons.toString())
      })
      .catch((error) => {
        new Error(error)
      })
  }
  // 退出登录
  async function logout() {
    username.value = ''
    avatar.value = ''
    permissions.value = ''
    token.value = ''
    buttons.value = ''
    localStorage.removeItem('avatar')
    localStorage.removeItem('username')
    localStorage.removeItem('token')
    localStorage.removeItem('permissions')
    localStorage.removeItem('buttons')
  }
  return { login, avatar, username, permissions, token, buttons, logout }
})
